import { useEffect, useRef, useState } from 'react';
import { PageContainer, ProTable, ModalForm } from '@ant-design/pro-components'
import type { ActionType } from '@ant-design/pro-components'
import { EditOutlined, DeleteOutlined, UnorderedListOutlined, CaretRightOutlined } from '@ant-design/icons'
import { Button, Row, Col, Tag, Tree, message } from 'antd';
import { GetRoleFnc, ShowRightFnc, SetRightFnc, DeleteRoleChildFnc } from '@/services/roles'
import style from './index.less'
import EditBox from './components/Edit'


const Roles = () => {
  const actionRef: any = useRef<ActionType>()
  const [messageApi, contextHolder] = message.useMessage()

  const [roleName, setRoleName] = useState('') // roleName
  const [roleDesc, setRoleDesc] = useState('') // roleDesc
  const [isModalOpen, setIsModalOpen] = useState(false) // 添加修改用户的盒子  
  const [id, setID] = useState('') // roleID 编辑盒子使用
  const [pageSize, setPageSize] = useState(2); // table 每页显示的条数
  const [current, setCurrent] = useState(1);
  const [giveModalOpen, setGiveModalOpen] = useState(false) // 分配角色的盒子  
  const [treeData, setTreeData] = useState([]) // 树形数据
  const [defkeys, setDefkeys] = useState<any>([]) // 选中的节点ID数值


  // 分配角色盒子 tree数据
  const init = async () => {
    const res = await ShowRightFnc()
    setTreeData(res.data)
  }
  useEffect(() => { init() }, [])

  // table数据初始化
  const getData = async () => {
    const res = await GetRoleFnc()
    let arr = []
    arr = res.data.map((item: any) => {
      return {
        key: item.id,
        id: item.id,
        roleName: item.roleName,
        roleDesc: item.roleDesc,
        sub: item.children // 这里的sub 不能取名叫children
      }
    })
    return {
      data: arr,
      success: res.meta.status === 200
    };
  }

  // 删除tag
  const deleteTag = async (tagID: number) => {
    const res = await DeleteRoleChildFnc(parseInt(id), tagID)
    if(res.meta.status === 200) {
      messageApi.success('更新成功', 1.5, () => {
        actionRef.current?.reload();
      })
    }
  }

  // 展开行获得数据
  const subTabLine = (record: {sub: []}) => {
    return record.sub.map((item: {children: [], id: number, authName: string}) => {
      if(item.children.length !== 0) {
        return (
          <Row key={item.id} className={style.row}>
            <Col span={6} className={style.centerCol}>
              <Tag color='blue' closable onClose={() => deleteTag(item.id)}>{item.authName}</Tag>
              <CaretRightOutlined/>
            </Col>

            <Col span={18}>
              {item.children.map((itemB: {children: [], id: number, authName: string}) => {
                return (
                  <Row key={itemB.id}>
                    <Col span={6}>
                      <Tag color='green' closable onClose={() => deleteTag(itemB.id)}>{itemB.authName}</Tag>
                      <CaretRightOutlined/>
                    </Col>
                    <Col span={18}>
                      {itemB.children.map((itemC: {id: number, authName: string}) => {
                        return (
                          <Tag className={style.lastTag} key={itemC.id} color='volcano' closable onClose={() => deleteTag(itemC.id)}>{itemC.authName}</Tag>
                        )
                      })}
                    </Col>
                  </Row> 
                )
              })}
            </Col>
          </Row>
        )
      } 
    })    
  }

  // 修改盒子 给子组件使用
  const changeDialog = (flag: boolean, ...args: any) => {
    setIsModalOpen(flag)
    setID(args[0])
    setRoleName(args[1])
    setRoleDesc(args[2])
  }

  // 删除角色
  const deleteRoles = () => {
   if (100 % pageSize === 1) { // 100代表 total 这里自己就是举个例子
    setCurrent(current - 1);
   }
  }

  const getLeafKeys = (node: {children: [], id: number}, arr: number[]) => { // 通过递归的形式获取角色下所有三级权限的ID并保存到数组中
    if (!node.children) {
       if(arr.includes(node.id)){
         return false
       } else {
          return arr.push(node.id) // 将number转为字符串
       }
    }
    node.children.forEach((item: {children: [], id: number}) => {
        getLeafKeys(item, arr)
    })
  }

  // 打开分配角色盒子
  const openGiveBox = (record: {id: string, roleName: string, roleDesc: string, sub: []}) => {
    setGiveModalOpen(true)
    setID(record.id)
    let obj: any = { // 因为getLeafKeys需要遍历children，而item对象里面是subs，所以要把subs属性名改为children
      id: record.id,
      roleName: record.roleName,
      roleDesc: record.roleDesc,
      children: record.sub,
    }
    getLeafKeys(obj, defkeys)
  }

  // 分配角色
  const roleOK = async () => {
    let keys = defkeys
    let rids = keys.join(',')
    const res = await SetRightFnc(parseInt(id), {rids: rids})
    if(res.meta.status === 200) {
      messageApi.success('更新成功', 1.5, () => {
        setGiveModalOpen(false) 
        actionRef.current?.reload();
      })
    }
  }

  const columns = [
    {title: '角色ID', dataIndex: 'id', key: 'id', width: 100},
    {title: '角色名称', dataIndex: 'roleName', key: 'roleName', width: 170, ellipsis: true},
    {title: '角色描述', dataIndex: 'roleDesc', key: 'roleDesc', width: 130, ellipsis: true},
    {title: '操作', width: 250, render: (_:any, record: {id: string, roleName: string, roleDesc: string, sub: []}) => {
      return (
       <>
        <Button type='primary' size='small' icon={<EditOutlined/>} onClick={() => changeDialog(true, record.id, record.roleName, record.roleDesc)}>编辑</Button> 
        <Button type="primary" danger size='small' icon={<DeleteOutlined/>} onClick={() => deleteRoles()} style={{margin: '0 6px 0'}}>删除</Button> 
        <Button color="yellow" variant="solid" size='small' icon={<UnorderedListOutlined/>} onClick={() => openGiveBox(record)}>设置</Button>
       </>
      )
    }}
  ]

  return (
    <>
      {contextHolder}
      {/* table */}
      <PageContainer header={{title: '', breadcrumb: { items: [{ title: '权限管理' }, { title: '角色列表' }] }}}>
        <ProTable columns={columns} actionRef={actionRef} request={async () => getData()} bordered search={false}
          expandable={{expandedRowRender: (record: any) => subTabLine(record),}}
          onChange={({ current }: any) => setCurrent(current)}
          pagination={{ pageSize: pageSize, showSizeChanger: true, pageSizeOptions: [2, 5, 10], onShowSizeChange: (_, size) => setPageSize(size)}}
        />
      </PageContainer>

       {/* 编辑角色盒子 */}
       <EditBox isModalOpen={isModalOpen} changeDialog={changeDialog} id={id} roleName={roleName} roleDesc={roleDesc} actionRef={actionRef}/>
       
       {/* 分配角色盒子 */}
       <ModalForm  title="分配权限" width={500} onFinish={roleOK} open={giveModalOpen} modalProps={{onCancel: () => setGiveModalOpen(false) }}>
        <Tree treeData={treeData} checkable defaultCheckedKeys={defkeys} fieldNames={{title: 'authName', key: 'id', children: 'children'}}
        onCheck={(checkedKeys: any, e: any) => setDefkeys([...checkedKeys, ...e.halfCheckedKeys])}/>
      </ModalForm>
    </>
  )
}

export default Roles